package us.nchu.tomtiger.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import us.nchu.tomtiger.model.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * Created by XiongXuan on 2018/1/6.
 */
@Component
public class UserUtil {
    private static int TIME_DELAY_LIMIT;

    // spring中不支持直接进行静态变量值的注入，这里利用spring的set注入方法，通过非静态的setter方法注入静态变量
    @Value("${app.config.time_delay_limit}")
    public void setTimeDelayLimit(int timeDelayLimit) {
        UserUtil.TIME_DELAY_LIMIT = timeDelayLimit;
    }

    /**
     * 写入已登录用户的参数
     * @param httpServletRequest
     */
    public static void writeUserInfo(HttpServletRequest httpServletRequest, User user) {
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute("userId", user.getPhoneNumber());
        session.setAttribute("nickName", user.getNickName());
    }

    public static String getUserPhoneNumber(HttpServletRequest httpServletRequest) {
        return (String) httpServletRequest.getSession().getAttribute("userId");
    }

    public static void goToLogin(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.sendRedirect("/login?ref=" + httpServletRequest.getRequestURL());
    }

    /**
     * 判断用户是否已经登录
     * @param httpServletRequest
     * @return
     */
    public static boolean isLogin(HttpServletRequest httpServletRequest) {
        String userId = (String) httpServletRequest.getSession().getAttribute("userId");
        return userId != null;
    }

    /**
     * 检查传入的时间是否在规定时间内
     * @param time
     * @return
     */
    public static boolean checkTime(String time) {
        Date cur = new Date();
        return Math.abs(Long.parseLong(time) - cur.getTime()) <= TIME_DELAY_LIMIT;
    }

    public static boolean checkTime(int time) {
        Date cur = new Date();
        return Math.abs(time - cur.getTime()) <= TIME_DELAY_LIMIT;
    }

    public static boolean checkTime(long time) {
        Date cur = new Date();
        return Math.abs(time - cur.getTime()) <= TIME_DELAY_LIMIT;
    }
}
